<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')"
             :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm"
             @keyup.enter.native="dataFormSubmitHandle()"
             :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'">
      <el-upload
          :action="url"
          :file-list="fileList"
          drag
          multiple
          :before-upload="beforeUploadHandle"
          :on-success="successHandle"
          class="text-center">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text" v-html="$t('upload.text')"></div>
        <div class="el-upload__tip" slot="tip">{{ $t('upload.tip', { 'format': 'jpg、png、gif' }) }}</div>
      </el-upload>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="visible = false">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import Cookies from "js-cookie";

export default {
  data() {
    return {
      visible: false,
      dataForm: {
        fid:'',
        id: '',
      }
    }
  },
  methods: {
    // 上传之前
    beforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error(this.$t('upload.tip', { 'format': 'jpg、png、gif' }))
        return false
      }
      this.num++
    }, // 上传成功
    successHandle (res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.fileList = fileList
      this.num--
      if (this.num === 0) {
        this.$message({
          message: this.$t('prompt.success'),
          type: 'success',
          duration: 500,
          onClose: () => {
            this.visible = false
            this.$emit('refreshDataList')
          }
        })
      }
    },
    init() {
      this.visible = true
      let fid = "&fid="+this.dataForm.fid;
      this.url = `${window.SITE_CONFIG['apiURL']}/biz/filestore/upload?token=${Cookies.get('token')+fid}`
      this.num = 0
      this.fileList = []
      console.log(this.dataForm.fid)
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
      })
    },
  }
}
</script>
